package com.hzqy.web.ac.epg;

import com.alibaba.fastjson.JSONObject;
import com.hzqy.commons.utils.WChatUtils;
import com.hzqy.service.epg.AcIptvListServiceBean;
import com.hzqy.service.epg.WchatService;
import com.hzqy.web.login.SessionKey;
import com.hzqy.web.vo.AcWinningVo;
import com.hzqy.web.vo.epg.AcIptvListVo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/*
 * 环球现网服务器使用
 */
@Controller
@RequestMapping("/iptv")
public class AcIptvListAction {
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	@Resource
	private AcIptvListServiceBean iptvServiceBean;

	/**
	 * 边锋活动服务器IP地址
	 * @return
	 */
	@RequestMapping("/getDomain")
    @ResponseBody
    public static String getDomain(){
        return WchatService.getDomain();
    }
	/**
	 * 查询总数
	 * @param session
	 * @param ailv f_iptv_activityid 活动id ,f_iptv_stats 状态
	 * @return
	 */
	@RequestMapping("/selectCount")
	@ResponseBody
	public Object selectCountActivityid(HttpSession session,AcIptvListVo ailv) {
		String userId = (String) session.getAttribute(SessionKey.SESSION_SERVERID);
		ailv.setF_iptv_serverid(userId);
		int count = iptvServiceBean.selectCountActivityid(ailv);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("count", count);
		return map;
	}
	
	/**
	 * 插入流水记录
	 * @param activityCode 活动编码 :用户管理系统提供
	 * @param extraCode 附加编码 :用户管理系统提供
	 * @param ailv  f_iptv_activityid 活动id,f_iptv_desc 描述,
	 *              f_iptv_votenum tv币数目,f_iptv_stats 状态:1获得；2消耗
	 * @return state： 0 成功；1 失败
	 */
	@RequestMapping("/insertIptvList")
	@ResponseBody
	public Object insertIptvList( HttpServletRequest request,AcIptvListVo ailv,String activityCode,String extraCode) {
		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute(SessionKey.SESSION_SERVERID);
		ailv.setF_iptv_serverid(userId);
		String secretKey =epgCommonAction.getEPGSecretKey(userId);
		String serverPath = getDomain();
		String QRCodeUrl = serverPath+"/mobile/iptv/actionReport.do?secretKey="+secretKey+"&iptvAccount="+userId+"&activityCode="+activityCode+"&extraCode="+extraCode;
		LOG.debug("上报签到URL--userId:"+userId+";QRCodeUrl:"+QRCodeUrl);
		JSONObject resultJson = null;
		try {
			String iptv = WChatUtils.sendGet(QRCodeUrl);
			resultJson = JSONObject.parseObject(iptv);
		} catch (Exception e) {
			LOG.debug("error:");
		}
		LOG.debug("上报签到、报名、投票行为：userId:"+userId+",结果"+resultJson);
		int id = 0;
		//当上报成功时本地存储，测试时无论成功与否都存储记录
		if (resultJson!=null&&"200".equals(resultJson.get("status").toString())) {
			ailv.setF_iptv_votenum(Integer.valueOf(resultJson.get("date").toString()));
			id = iptvServiceBean.insertIptvList(ailv);
		}else {
			id = iptvServiceBean.insertIptvList(ailv);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if(id>0) {
			map.put("state", 0);
			map.put("msg", "success");
			map.put("id", id);
		}else {
			map.put("state", 1);
			map.put("msg", "error");
		}
		return map;
	}
	/**
	 * （活动）产品包订购数据上报
	 * @param productCode 订购产品编码
	 * @param startTime 订购开始时间   格式：yyyyMMddHHmmss
	 * @param endTime 订购到期时间   格式：yyyyMMddHHmmss
	 * @return
	 */
	@RequestMapping("/sendIptvOrder")
	@ResponseBody
	public Object sendIptvOrder(HttpServletRequest request,String productCode,String startTime,String endTime) {
		HttpSession session = request.getSession();
		String iptvAccount = (String) session.getAttribute(SessionKey.SESSION_SERVERID);
		String secretKey =epgCommonAction.getEPGSecretKey(iptvAccount);//接口调用密钥后台生成
		String serverPath = getDomain();
		String QRCodeUrl = serverPath+"/mobile/iptv/orderReportEx.do?secretKey="+secretKey+"&iptvAccount="+iptvAccount+"&productCode="+productCode+"&startTime="+startTime+"&endTime="+endTime;
		LOG.debug("订购上报URL--userId:"+iptvAccount+",QRCodeUrl:"+QRCodeUrl);
		String iptv = WChatUtils.sendGet(QRCodeUrl);
		JSONObject resultJson = JSONObject.parseObject(iptv);
		LOG.debug("产品包订购数据上报：userId:"+iptvAccount+",结果"+resultJson);
		Map<String, Object> map = new HashMap<String, Object>();
		if ("200".equals(resultJson.get("status").toString())) {
			//绑定成功
			map.put("flag", "success");
		}else {
			map.put("flag", "error");
		}
		return map;
	}
	/**
	 * 3.17系统用户积分查询
	 * @param request
	 * @return
	 */
	@RequestMapping("/getUserPoints")
	@ResponseBody
	public Object getUserPoints(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String iptvAccount = (String) session.getAttribute(SessionKey.SESSION_SERVERID);
		String secretKey =epgCommonAction.getEPGSecretKey(iptvAccount);//接口调用密钥后台生成
		String serverPath = getDomain();
		String QRCodeUrl = serverPath+"/mobile/iptv/pointsSelect.do?secretKey="+secretKey+"&iptvAccount="+iptvAccount;
		String iptv = WChatUtils.sendGet(QRCodeUrl);
		JSONObject resultJson = JSONObject.parseObject(iptv);
		LOG.debug("系统用户积分查询：userId:"+iptvAccount+",结果"+resultJson);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pointsTotal", resultJson.get("pointsTotal"));
		map.put("message", resultJson.get("message"));
		map.put("error", resultJson.get("error"));
		map.put("status", resultJson.get("status"));
		return map;
	}
	/**
	 * 3.16积分消费同步
	 * @param request
	 * @return
	 */
	@RequestMapping("/pointsConsume")
	@ResponseBody
	public Object pointsConsume(HttpServletRequest request,String activityCode,
			String extraCode,String remark,int points,String activityid ) {
		HttpSession session = request.getSession();
		String iptvAccount = (String) session.getAttribute(SessionKey.SESSION_SERVERID);
		String secretKey =epgCommonAction.getEPGSecretKey(iptvAccount);//接口调用密钥后台生成
		String serverPath = getDomain();
		String QRCodeUrl = serverPath+"/mobile/iptv/pointsConsume.do?secretKey="+secretKey+"&iptvAccount="+iptvAccount
				+"&activityCode="+activityCode+"&extraCode="+extraCode+"&remark="+remark+"&points="+points;
		String iptv = WChatUtils.sendGet(QRCodeUrl);
		JSONObject resultJson = JSONObject.parseObject(iptv);
		LOG.debug("积分消费同步：userId:"+iptvAccount+",结果"+resultJson);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("data", resultJson.get("data"));
		map.put("message", resultJson.get("message"));
		map.put("error", resultJson.get("error"));
		map.put("status", resultJson.get("status"));
		//本地备份数据记录
		AcIptvListVo ailv = new AcIptvListVo();
		ailv.setF_iptv_serverid(iptvAccount);
		ailv.setF_iptv_activityid(activityid);
		ailv.setF_iptv_desc(remark);
		ailv.setF_iptv_stats(2);
		ailv.setF_iptv_votenum(points);
		int id = iptvServiceBean.insertIptvList(ailv);
		return map;
	}
	
	/**
	 * 3.16积分产生同步
	 * @param request
	 * @return
	 */
	@RequestMapping("/pointsProduce")
	@ResponseBody
	public Object pointsProduce(HttpServletRequest request,String activityCode,
			String extraCode,String remark,int points,String activityid ) {
		HttpSession session = request.getSession();
		String iptvAccount = (String) session.getAttribute(SessionKey.SESSION_SERVERID);
		Map<String, Object> map = iptvServiceBean.pointsProduce(iptvAccount,activityCode,
				extraCode,remark,points,activityid);
		return map;
	}
	
	/**
	 * （活动）产品包订购数据上报
	 * @param productCode 订购产品编码
	 * @param type 积分订购类型：0：产品包；1：专区；2：单片
	 * @return
	 */
	@RequestMapping("/pointsOrder")
	@ResponseBody
	public Object pointsOrder(HttpServletRequest request,String productCode,String type) {
		HttpSession session = request.getSession();
		String iptvAccount = (String) session.getAttribute(SessionKey.SESSION_SERVERID);
		String secretKey =epgCommonAction.getEPGSecretKey(iptvAccount);//接口调用密钥后台生成
		String serverPath = getDomain();
		//获取当前日期
		Date date= new Date();	
		//创建Calendar实例
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MONTH, 1);
		//将时间格式化成yyyyMMddHHmmss的格式
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

		String startTime = format.format(date);
		String endTime = format.format(calendar.getTime());
		
		String QRCodeUrl = serverPath+"/mobile/iptv/pointsOrder.do?secretKey="+secretKey+"&iptvAccount="+iptvAccount+"&productCode="+productCode+"&startTime="+startTime+"&endTime="+endTime+"&type="+type;
		LOG.debug("积分抽奖产品包订购URL--userId:"+iptvAccount+",QRCodeUrl:"+QRCodeUrl);
		String iptv = WChatUtils.sendGet(QRCodeUrl);
		JSONObject resultJson = JSONObject.parseObject(iptv);
		LOG.debug("积分抽奖产品包订购：userId:"+iptvAccount+",结果"+resultJson);
		Map<String, Object> map = new HashMap<String, Object>();
		if ("200".equals(resultJson.get("status").toString())) {
			map.put("flag", "success");
		}else {
			map.put("flag", "error");
		}
		return map;
	}
	/**
	 * （活动）产品包订购数据信息提醒
	 * @param productCode 订购产品编码
	 * @param startTime 订购开始时间   格式：yyyyMMddHHmmss
	 * @param endTime 订购到期时间   格式：yyyyMMddHHmmss
	 * @return
	 */
	@RequestMapping("/sendIptvOrderInfo")
	@ResponseBody
	public Object sendIptvOrderInfo(HttpServletRequest request,String productCode) {
		HttpSession session = request.getSession();
		String iptvAccount = (String) session.getAttribute(SessionKey.SESSION_SERVERID);
		String secretKey =epgCommonAction.getEPGSecretKey(iptvAccount);//接口调用密钥后台生成
		String serverPath = getDomain();
		String QRCodeUrl = serverPath+"/mobile/iptv/orderReport.do?secretKey="+secretKey+"&iptvAccount="+iptvAccount+"&productCode="+productCode;
		LOG.debug("订购信息URL--userId:"+iptvAccount+",QRCodeUrl:"+QRCodeUrl);
		String iptv = WChatUtils.sendGet(QRCodeUrl);
		JSONObject resultJson = JSONObject.parseObject(iptv);
		LOG.debug("产品包订购信息提醒：userId:"+iptvAccount+",结果"+resultJson);
		Map<String, Object> map = new HashMap<String, Object>();
		String info="";
		if ("200".equals(resultJson.get("status").toString())) {
			//绑定成功
			map.put("flag", "success");
			map.put("data", resultJson.get("data"));
		}else {
			map.put("flag", "error");
		}
		return map;
	}
	/**
	 * （活动）环球调用边锋服务器iptv接口  收货地址查询
	 * @param secretKey
	 * @param iptvAccount
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/addressList")
	@ResponseBody
	public Object addressList(HttpServletRequest request,AcWinningVo awv) {
		HttpSession session = request.getSession();
		String iptvAccount = (String) session.getAttribute(SessionKey.SESSION_SERVERID);
		String serverPath = getDomain();
		String QRCodeUrl = serverPath+"mobile/iptv/addressList.do?iptvAccount="+iptvAccount+"&f_awl_activityid="+awv.getF_awl_activityid()+"&f_awl_prizeid="+awv.getF_awl_prizeid();
		LOG.debug("收货地址查询URL--userId:"+iptvAccount+",QRCodeUrl:"+QRCodeUrl);
		JSONObject resultJson=null;
		try {
			String iptv = WChatUtils.sendGet(QRCodeUrl);
			resultJson = JSONObject.parseObject(iptv);
		} catch (Exception e) {
			LOG.error("请求微信服务器error:"+e);
		}
		LOG.debug("收货地址查询URL：userId:"+iptvAccount+",结果"+resultJson);
		Map<String, Object> map = new HashMap<String, Object>();
		if (resultJson!=null && !"".equals(resultJson.get("address").toString())) {
			map.put("flag", "success");
			map.put("address", resultJson.get("address"));
			map.put("receiver", resultJson.get("receiver"));
			map.put("telephone", resultJson.get("telephone"));
		}else {
			map.put("flag", "error");
			map.put("address", "");
			map.put("receiver", "");
			map.put("telephone", "");
		}
		return map;
	}
	/**
	 * （活动）同步奖品
	 * @param secretKey
	 * @param iptvAccount
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/addAward")
	@ResponseBody
	public Object addAward(HttpServletRequest request,String activityCode,String goodsCode) {
		HttpSession session = request.getSession();
		String iptvAccount = (String) session.getAttribute(SessionKey.SESSION_SERVERID);
		Map<String, Object> map = iptvServiceBean.addAward(iptvAccount,activityCode,goodsCode);
		return map;
	}
	/**
	 * （活动）环球调用边锋服务器iptv接口  收货地址新增（手机号码同步）
	 * @param secretKey
	 * @param iptvAccount
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/insertAddress")
	@ResponseBody
	public Object insertAddress(HttpServletRequest request,AcWinningVo awv) {
		HttpSession session = request.getSession();
		String iptvAccount = (String) session.getAttribute(SessionKey.SESSION_SERVERID);
		String serverPath = getDomain();
		String QRCodeUrl = serverPath+"mobile/iptv/insertAddress.do?f_awl_serverid="+awv.getF_awl_serverid()+"&f_awl_activityid="+awv.getF_awl_activityid()
		+"&f_awl_prizeid="+awv.getF_awl_prizeid()+"&f_awl_userphone="+awv.getF_awl_userphone()+"&f_awl_prizename="+awv.getF_awl_prizename();
		LOG.debug("收货地址新增URL--userId:"+awv.getF_awl_serverid()+",Url:"+QRCodeUrl);
		JSONObject resultJson=null;
		try {
			String iptv = WChatUtils.sendGet(QRCodeUrl);
			resultJson = JSONObject.parseObject(iptv);
		} catch (Exception e) {
			LOG.error("请求微信服务器error:"+e);
		}
		LOG.debug("收货地址新增：userId:"+iptvAccount+",结果"+resultJson);
		Map<String, Object> map = new HashMap<String, Object>();
		if (resultJson!=null && resultJson.get("status")!=null && "200".equals(resultJson.get("status").toString())) {
			map.put("status", "200");
		}else {
			map.put("status", "500");
		}
		return map;
	}
}
